package com.example.chuzhou.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.example.chuzhou.constans.CommonConstans.NO_LOGIN;

public class HttpRequest {

    public static final int timeout = 40;

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            System.out.println(urlNameString);
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setConnectTimeout(timeout * 1000);
            connection.setReadTimeout(timeout * 1000);
            connection.setRequestProperty("content-type", "application/json");
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
//            logger.warning("发送GET请求出现异常！",e);
            System.out.println(e);
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    public static String httpPostData(String uri, String postData, HttpServletRequest request) {
        String retStr = null;
        try {
            HttpParams httpParams = new BasicHttpParams();
            httpParams.setParameter("charset", "UTF-8");
            HttpConnectionParams.setConnectionTimeout(httpParams, timeout * 1000);  //毫秒
            HttpConnectionParams.setSoTimeout(httpParams, timeout * 1000);
            HttpClient httpClient = new DefaultHttpClient(httpParams);

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader("content-type", "application/x-www-form-urlencoded");
            httpPost.setHeader("clientIP", request.getRemoteAddr());
            httpPost.setEntity(new StringEntity(postData, "UTF-8"));
            HttpResponse response;
            response = httpClient.execute(httpPost);
//            System.out.println("response========>"+response);
            int code = response.getStatusLine().getStatusCode();
//            if (code == 200) {
            retStr = EntityUtils.toString(response.getEntity(), "UTF-8");
//            }
        } catch (Exception e) {
            e.printStackTrace();
//            logger.error("post请求失败：",e);
        }
        return retStr;
    }

    public static String httpPostData(String uri, String postData, String authorization, HttpServletRequest request) {
        return postData(uri, postData, authorization, "application/x-www-form-urlencoded", request);
    }

    public static String httpPostDataJson(String uri, String postData, String authorization, HttpServletRequest request) {
        return postData(uri, postData, authorization, "application/json", request);
    }

    public static String postData(String uri, String postData, String authorization, String contentType, HttpServletRequest request) {
        String retStr = null;
        try {
            HttpParams httpParams = new BasicHttpParams();
            httpParams.setParameter("charset", "UTF-8");
            httpParams.setParameter("authorization", authorization);
            HttpConnectionParams.setConnectionTimeout(httpParams, timeout * 1000);  //毫秒
            HttpConnectionParams.setSoTimeout(httpParams, timeout * 1000);
            HttpClient httpClient = new DefaultHttpClient(httpParams);

            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader("Content-type", contentType);
            httpPost.setHeader("Authorization", authorization);
            httpPost.setHeader("clientIP", request.getRemoteAddr());
            httpPost.setEntity(new StringEntity(postData, "UTF-8"));
            HttpResponse response;
            response = httpClient.execute(httpPost);
            int code = response.getStatusLine().getStatusCode();
            if (code == 200 || code == 500) {
                retStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            } else if (code == 401) {
                Map<String, Object> result = new HashMap<>();
                result.put("code", NO_LOGIN);
                result.put("message", "用户未登录！");
                result.put("success", false);
                retStr = JSONObject.toJSONString(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
//            logger.error("post请求失败：",e);
        }
        return retStr;
    }

    public static String httpPostData(String uri, List<BasicNameValuePair> postData) {
        String res = "";
        try {
            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=utf-8");
            httpPost.setEntity(new UrlEncodedFormEntity(postData, "utf-8"));
            RequestConfig config = RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(15000).build();
            HttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
            HttpResponse httpResponse = httpClient.execute(httpPost);
            res = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
            System.out.println(res);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

}
